from django.shortcuts import render
from drf_haystack.viewsets import HaystackGenericAPIView, ListModelMixin, HaystackViewSet
from haystack.views import SearchView
from rest_framework.generics import ListAPIView, RetrieveAPIView, CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from article.models import Channel, Article
from article.serializer import ChannelSerializer, ArticleSerializer, DetailArticleSerializer, CommentSerializer, \
        ArticleIndexSerializer
from article.utils import PageNum


class ChannelList(ListAPIView):
    """频道列表"""

    queryset = Channel.objects.all()
    serializer_class = ChannelSerializer
    pagination_class = PageNum


class ArticleList(RetrieveAPIView):
    """文章列表"""

    queryset = Article.objects.all()
    serializer_class = ArticleSerializer
    pagination_class = PageNum


class ArticleCreate(CreateAPIView):
    """发布文章"""

    queryset = Article.objects.all
    serializer_class = ArticleSerializer


class CollectedArticles(APIView):
    """收藏和取消收藏文章"""

    def put(self, request, pk):

        try:
            # 查询数据库是否有这一条记录
            collected_articles = request.user.collected_articles.get(article_id=pk)
        except Exception as e:
            # 如果没有视为 收藏

            try:
                article = Article.objects.get(id=pk)
                request.user.collected_articles.add(article)
            except Exception as e:
                return Response({'success': False,
                                 'message': '数据库操作失败'})

            return Response({'success': True,
                             'message': '收藏成功'})

        # 如果有视为 取消收藏
        try:
            article = Article.objects.get(id=pk)
            request.user.collected_articles.remove(article)
        except Exception as e:
            return Response({'success': False,
                             'message': '数据库操作失败'})

        return Response({'success': True,
                         'message': '取消收藏成功'})


class DetailArticle(RetrieveAPIView):
    """文章详情"""

    queryset = Article.objects.all()
    serializer_class = DetailArticleSerializer

    def get(self, requset, pk):
        article = self.get_object()
        article.visits += 1
        article.save()
        super().get(requset, pk)


class Comment(CreateAPIView):
    """评论文章"""

    serializer_class = CommentSerializer


# class MySearchView(HaystackViewSet):
class MySearchView(HaystackGenericAPIView, ListModelMixin):
    """根据关键字搜索文章"""

    index_models = Article
    serializer_class = ArticleIndexSerializer
    pagination_class = PageNum

    def get(self, request):
        return self.list(request)



